﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Shine.Util;
using System.IO;
using SuperMap.Data;
using SuperMap.Realspace;
using Shine.Framework;
using System.Collections;


namespace Shine.Viewer
{
    public partial class ViewSpotListUserForm : UserControl
    {
        //static readonly string bookmarkFileName = @"bookmark.xml";
        //static readonly string bookmarkFile = System.IO.Directory.GetCurrentDirectory() + "\\ViewSpot\\" + bookmarkFileName;
        string currentBookmarkFile = string.Empty;
        static readonly string bookmarkBlankImage = @"blank.png";
        string currentSelectedBookMarkUniCode = string.Empty;
        Scene currentScene = null;
        IApplication application = null;

        public ViewSpotListUserForm(IApplication m_Application)
        {
            InitializeComponent();
            this.application = m_Application;
        }

        private void ViewSpotListUserForm_Load(object sender, System.EventArgs e)
        {
            currentScene = (application as IFramework).SceneControl.Scene;
        }

        /// <summary>
        /// 初始化书签管理器
        /// </summary>
        public void LoadBookmarks(string filename)
        {
            if (filename != null)
            {
                this.currentBookmarkFile = filename;
            }
            else
            {
                return;
            }

            if (File.Exists(currentBookmarkFile))
            {
                Stack<RealspaceBookMarkStruck> bookmarkObjs = new Stack<RealspaceBookMarkStruck>();
                书签管理 bkm = null;
                // 加载bookmark
                try
                {
                    bkm = Shine.Util.Configurations.ConfigurationHelper.GetObjectFromXml<书签管理>(currentBookmarkFile);
                }
                catch (Exception ex)
                {
                    return;
                }

                if(bkm != null)
                {
                    foreach(var bk in bkm.items)
                    {
                        // 书签名称
                        string name = bk.Name.Trim();
                        // 书签编号
                        string code = bk.UniCode.Trim();
                        // 当前视角高度
                        double altitude = String.IsNullOrEmpty(bk.Altitude) ? 0 : Convert.ToDouble(bk.Altitude);
                        // 当前视角模式
                        string altitudeMode = bk.AltitudeMode;
                        // 当前视角旋转角度
                        double heading = string.IsNullOrEmpty(bk.Heading) ? 0 : Convert.ToDouble(bk.Heading);
                        // 当前视角俯视角度
                        double tile = string.IsNullOrEmpty(bk.Tilt) ? 0 : Convert.ToDouble(bk.Tilt);
                        // 当前视角经度
                        double longitude = string.IsNullOrEmpty(bk.Longitude) ? 0 : Convert.ToDouble(bk.Longitude);
                        // 当前视角纬度
                        double latitude = string.IsNullOrEmpty(bk.Latitude) ? 0 : Convert.ToDouble(bk.Latitude);
                        // 场景图片路径
                        string imageFile = bk.ImagePath.Trim();

                        // 如果imageFile不存在（被误删），用替代图像
                        if(!File.Exists(imageFile))
                        {
                            imageFile = System.IO.Directory.GetCurrentDirectory() + "\\ViewSpot\\" + bookmarkBlankImage;
                        }

                        Camera camera = new Camera
                        {
                             Altitude = altitude,
                             Tilt = tile,
                             Heading = heading,
                             Latitude = latitude,
                             Longitude = longitude,
                             AltitudeMode = GetAltitudeMode(altitudeMode)
                        };

                        RealspaceBookMarkStruck bkstruct = new RealspaceBookMarkStruck
                        {
                            ca = camera,
                            bkname = name,
                            bkunicode = code,
                            bkfile = imageFile
                        };

                        bookmarkObjs.Push(bkstruct);
                        //this.InsertSingleBookmarkUserForm(bkstruct);
                    }

                    this.AddBookmarkToControl(bookmarkObjs);
                }

            }

        }

        /// <summary>
        /// 加载bookmarks
        /// </summary>
        /// <param name="bookmarks"></param>
        private void AddBookmarkToControl(Stack<RealspaceBookMarkStruck> bookmarks)
        {
            Stack<RealspaceBookMarkStruck> bookmarkCollection = bookmarks;
            int count = bookmarkCollection.Count;

            if (this.Controls.Count > 0)
            {
                this.Controls.Clear();
            }

            for (int index = 0; index < count; index ++)
            {
                RealspaceBookMarkStruck bks = bookmarkCollection.Pop();
                this.InsertSingleBookmark(bks);
            }

        }

        /// <summary>
        /// 新增或删除书签后更新书签管理器
        /// 1. 更新xml
        /// </summary>
        private void UpdateBookMarkBar()
        {
            书签管理 bkm = new 书签管理();
            List<三维书签> bookmarks = new List<三维书签>();
            bkm.items = bookmarks;

            foreach (var obj in this.Controls)
            {
                RealspaceBookMarkStruck bks = (obj as SingleBookmarkUserForm).BookMarkStruck;
                三维书签 bk = new 三维书签
                {
                    Altitude = bks.ca.Altitude.ToString(),
                    AltitudeMode = this.GetAltitudeModeCode(bks.ca.AltitudeMode),
                    Heading = bks.ca.Heading.ToString(),
                    Tilt = bks.ca.Tilt.ToString(),
                    Longitude = bks.ca.Longitude.ToString(),
                    Latitude = bks.ca.Latitude.ToString(),
                    Name = bks.bkname,
                    UniCode = bks.bkunicode,
                    ImagePath = bks.bkfile
                };
                bkm.items.Add(bk);
            }

            try
            {
                Shine.Util.Configurations.ConfigurationHelper.SaveObjectToXml<书签管理>(bkm, currentBookmarkFile, "Root");
            }
            catch(ArgumentNullException ex)
            {
                throw ex;
            }

        }

        private AltitudeMode GetAltitudeMode(string mode)
        {
            if (mode == "0")
                return AltitudeMode.ClampToGround;
            else if (mode == "1")
                return AltitudeMode.RelativeToGround;
            else if (mode == "2")
                return AltitudeMode.Absolute;
            else if (mode == "3")
                return AltitudeMode.RelativeToUnderground;
            else if (mode == "4")
                return AltitudeMode.AbsoluteUnderGround;
            else if (mode == "5")
                return AltitudeMode.ClampToObject;
            else if (mode == "6")
                return AltitudeMode.ModifyTerrain;
            else
                return AltitudeMode.Absolute;
        }

        private string GetAltitudeModeCode(AltitudeMode mode)
        {
            if (mode == AltitudeMode.ClampToGround)
                return "0";
            else if (mode == AltitudeMode.RelativeToGround)
                return "1";
            else if (mode == AltitudeMode.Absolute)
                return "2";
            else if (mode == AltitudeMode.RelativeToUnderground)
                return "3";
            else if (mode == AltitudeMode.AbsoluteUnderGround)
                return "4";
            else if (mode == AltitudeMode.ClampToObject)
                return "5";
            else if (mode == AltitudeMode.ModifyTerrain)
                return "6";
            else
                return "0";
        }
        
        /// <summary>
        /// 新增一个书签
        /// </summary>
        /// <param name="ca"></param>
        /// <param name="imageFile"></param>
        private void InsertSingleBookmark(RealspaceBookMarkStruck bks)
        {
            SingleBookmarkUserForm SingleBookmarkCtr = new SingleBookmarkUserForm(bks);
            SingleBookmarkCtr.UpdateBookmarkEventHandler += SingleBookmarkCtr_UpdateBookmarkEventHandler;
            SingleBookmarkCtr.UpdateSceneEventHandler += SingleBookmarkCtr_UpdateSceneEventHandler;

            int currentIndex = this.Controls.Count;
            SingleBookmarkCtr.Location = this.CalculatePictureBoxLocationByIndex(currentIndex);
            this.Controls.Add(SingleBookmarkCtr);
        }

        private void InsertBookmarkOnTop(RealspaceBookMarkStruck bks)
        {
            SingleBookmarkUserForm SingleBookmarkCtr = new SingleBookmarkUserForm(bks);
            SingleBookmarkCtr.UpdateBookmarkEventHandler += SingleBookmarkCtr_UpdateBookmarkEventHandler;
            SingleBookmarkCtr.UpdateSceneEventHandler += SingleBookmarkCtr_UpdateSceneEventHandler;

            SingleBookmarkUserForm[] ranges = new SingleBookmarkUserForm[this.Controls.Count + 1];
            int index = 0;
            ranges[index] = SingleBookmarkCtr;
            foreach (var obj in this.Controls)
            {
                index++;
                ranges[index] = obj as SingleBookmarkUserForm;
            }

            this.Controls.Clear();

            int index2 = 0;
            foreach (var obj in ranges)
            {
                ((SingleBookmarkUserForm)obj).Location = this.CalculatePictureBoxLocationByIndex(index2);
                this.Controls.Add(obj);
                index2++;
            }
        }

        private Point CalculatePictureBoxLocationByIndex(int index)
        {
            // 左侧和顶部留白
            Point Location = new Point(7, 130 * index + 5);
            return Location;
        }

        /// <summary>
        /// 用户点击image，触发事件：
        /// 1. 更新当前场景
        /// 2. 记录当前书签，便于删除操作
        /// </summary>
        /// <param name="bmk"></param>
        void SingleBookmarkCtr_UpdateSceneEventHandler(object sender, RealspaceBookMarkEventArgs e)
        {
            // 更新当前scene的定位
            Camera ca = e.CurrentBMS.ca;

            // 更新当前书签对应的picbox
            this.currentSelectedBookMarkUniCode = e.CurrentBMS.bkunicode;

            //FlyManager fm = (application as IFramework).SceneControl.Scene.FlyManager;
            //fm.PlayRate = fm.PlayRate * 10000;
            //this.currentScene.Fly(ca);
            //this.currentScene.Refresh();

            // 直接飞行
            this.currentScene.Camera = ca;
            this.currentScene.Refresh();
        }

        /// <summary>
        /// 保存书签事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void SingleBookmarkCtr_UpdateBookmarkEventHandler(object sender, BookMarkEventArgs e)
        {

            书签管理 bkm = Shine.Util.Configurations.ConfigurationHelper.GetObjectFromXml<书签管理>(currentBookmarkFile);
            int index = 0;

            for (int i = 0; i < bkm.items.Count; i++)
            {
                if (bkm.items[i].UniCode == e.CurrentBMK.UniCode)
                {
                    index = i;
                    break;
                }
            }

            bkm.items[index] = e.CurrentBMK;

            try
            {
                Shine.Util.Configurations.ConfigurationHelper.SaveObjectToXml<书签管理>(bkm, currentBookmarkFile, "Root");
            }
            catch(ArgumentNullException ex)
            { 
                throw ex; 
            }
        }

        /// <summary>
        /// 新增书签
        /// </summary>
        /// <param name="ca"></param>
        public void AddNewBookMark(RealspaceBookMarkStruck bms)
        {
            // 如果当前没有书签，先加载或者创建一个书签
            if (this.currentBookmarkFile == string.Empty)
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "视点管理文件(*.xml) | *.xml";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    currentBookmarkFile = dlg.FileName;
                }
                else
                {
                    return; 
                }
            }
            
            this.InsertBookmarkOnTop(bms);
            this.UpdateBookMarkBar();
            //书签管理 bkm = null;

            //三维书签 bk = new 三维书签
            //{
            //    Name = bms.bkname,
            //    UniCode = bms.bkunicode,
            //    Altitude = bms.ca.Altitude.ToString(),
            //    AltitudeMode = this.GetAltitudeModeCode(bms.ca.AltitudeMode),
            //    Heading = bms.ca.Heading.ToString(),
            //    Tilt = bms.ca.Tilt.ToString(),
            //    Latitude = bms.ca.Latitude.ToString(),
            //    Longitude = bms.ca.Longitude.ToString(),
            //    ImagePath = bms.bkfile
            //};

            //try
            //{
            //    bkm = Shine.Util.Configurations.ConfigurationHelper.GetObjectFromXml<书签管理>(currentBookmarkFile);
            //}
            //catch (ArgumentNullException ex)
            //{
            //    //throw ex;
            //}
            //finally
            //{
            //    if (bkm == null)
            //    {
            //        bkm = new 书签管理();
            //        List<三维书签> bookmarks = new List<三维书签>();
            //        bookmarks.Add(bk);
            //        bkm.items = bookmarks;
            //    }
            //    else
            //    {
            //        bkm.items.Add(bk);
            //    }

            //    Shine.Util.Configurations.ConfigurationHelper.SaveObjectToXml<书签管理>(bkm, currentBookmarkFile, "Root");
            //}
        }

        /// <summary>
        /// 移除书签
        /// </summary>
        /// <param name="bx"></param>
        public void RemoveBookMark()
        {
            if (this.currentSelectedBookMarkUniCode == string.Empty)
            {
                MessageBox.Show("请选择需要删除的视点.");
                return;
            }

            SingleBookmarkUserForm bx = this.UpdateCurrentSelectedBookmark(this.currentSelectedBookMarkUniCode);
            this.currentSelectedBookMarkUniCode = string.Empty;

            if(bx != null)
            {
                // 重新加载
                SingleBookmarkUserForm[] ranges = new SingleBookmarkUserForm[this.Controls.Count-1];
                int index = 0;
                foreach (var obj in this.Controls)
                {
                    if(bx.BookMarkStruck.bkunicode == (obj as SingleBookmarkUserForm).BookMarkStruck.bkunicode)
                    {
                        continue;
                    }
                    ranges[index] = obj as SingleBookmarkUserForm;
                    index++;
                }

                this.Controls.Clear();

                int index2 = 0;
                foreach (var obj in ranges)
                {
                    ((SingleBookmarkUserForm)obj).Location = this.CalculatePictureBoxLocationByIndex(index2);
                    this.Controls.Add(obj);
                    index2++;
                }

            }
            
            //TODO: 更新xml文件
            this.UpdateBookMarkBar();
        }

        /// <summary>
        /// 根据书签的unicode，返回对应的SingleBookmarkUserForm
        /// </summary>
        /// <param name="bookmarkunicode"></param>
        /// <returns></returns>
        private SingleBookmarkUserForm UpdateCurrentSelectedBookmark(string bookmarkunicode)
        {
            string unicode = bookmarkunicode;
            SingleBookmarkUserForm bx = null;

            foreach(var obj in this.Controls)
            {
                string code = ((SingleBookmarkUserForm)obj).BookMarkStruck.bkunicode;

                if (code == unicode)
                {
                    bx = (SingleBookmarkUserForm)obj;
                    break;
                }
            }

            return bx; 
        
        }

    }
}
